<template>
  <div>
    <!--面包屑导航区-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!--卡片视图区-->
    <el-card class="box-card">

       <!--搜索和添加区域-->
       <el-row :gutter="20">
         <el-col :span="7">
           <el-input placeholder="请输入内容" v-model="queryInfo.query" class="input-with-select" clearable @clear="getUserList">
              <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
           </el-input>
         </el-col>
         <el-col :span="4">
           <el-button type="primary"  @click="dialogVisible = true">添加</el-button>
         </el-col>
       </el-row>

       <!--用户列表区域-->
      <el-table
        size="mini"
        :data="userList"
        border stripe
        style="width: 100%">
        <el-table-column prop="id" label="编号"></el-table-column>
        <el-table-column prop="name" label="姓名"></el-table-column>
        <el-table-column prop="nickname" label="昵称"></el-table-column>
        <el-table-column prop="rolename" label="角色"></el-table-column>
        <el-table-column prop="phone" label="电话号码"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.isdel" @change="userStateChanged(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="日期">
          <template slot-scope="scope">
            {{getData(scope.row.addtime)}}
          </template>
        </el-table-column>
        <el-table-column
          fixed="right"
          label="操作"
          width="180">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)"></el-button>
            <el-tooltip class="item" effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="setUserRoles(scope.row)"></el-button>
            </el-tooltip>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="delUser(scope.row.id)"></el-button>
          </template>
        </el-table-column>
      </el-table>

      <!--分页区域-->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pageIndex"
        :page-sizes="[5, 10, 20, 50]"
        :page-size="queryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>

    <!--添加用户的对话框---begin-->
    <el-dialog
      title="添加用户"
      :visible.sync="dialogVisible"
      @close="addDialogClosed"
      width="50%">
      <!--内容主体区-->
      <el-form :model="addForm " :rules="addFormRules" ref="addFormRef" label-width="70px" :inline="true">
        <el-form-item label="用户名" prop="name">
          <el-input v-model="addForm.name"></el-input>
        </el-form-item>
        <el-form-item label="昵称">
          <el-input v-model="addForm.nickname"></el-input>
        </el-form-item>
        <el-form-item label="账号" prop="loginName">
          <el-input v-model="addForm.loginName"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="pwd">
          <el-input v-model="addForm.pwd"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="addForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="addForm.sex">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="0">女</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <!--底部区域-->
      <span slot="footer" class="dialog-footer">
        <el-button @click="resetAddUser">取 消</el-button>
        <el-button type="primary" @click="subAddUser">确 定</el-button>
      </span>
    </el-dialog>
    <!--添加用户的对话框---end-->

    <!--用户修改对话框--begin-->
    <el-dialog
      title="修改用户"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed">
      <!--内容主体区-->
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px" :inline="true">
        <el-form-item label="用户名" prop="name">
          <el-input v-model="editForm.name"></el-input>
        </el-form-item>
        <el-form-item label="昵称">
          <el-input v-model="editForm.nickname"></el-input>
        </el-form-item>
        <el-form-item label="账号">
          <el-input v-model="editForm.loginName" disabled></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="editForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="editForm.sex">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="0">女</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!--用户修改对话框--end-->

    <!--设置角色对话框-->
    <el-dialog
    title="设置角色"
    :visible.sync="setRolesdialogVisible"
    width="50%"
    @close="userRolesDialogClosed"
    >
    <div>
      <p>用户名称：{{setRotes.name}}</p>
      <p>当前角色：{{setRotes.rolesname}}</p>
      <p>
        设新角色：
        <el-select v-model="newUserRoles" placeholder="请选择">
          <el-option
            v-for="item in setRotes.rolesSelect"
            :key="item.id"
            :label="item.rolename"
            :value="item.id">
          </el-option>
        </el-select>
      </p>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="setRolesdialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="subSetUserRoles">确 定</el-button>
    </span>
  </el-dialog>

  </div>
</template>

<script>
export default {
  data () {
    // 验证邮箱的规则
    var checkEmail = (rule, value, cb) => {
      // 验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的邮箱'))
    }
    // 验证手机号码的规则
    var checkPhone = (rule, value, cb) => {
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regMobile.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的手机'))
    }
    return {
      // 获取用户列表的对象
      queryInfo: {
        query: '',
        pageIndex: 1,
        pageSize: 10
      },
      userList: [],
      total: 0,
      // 控制对话框的显示/隐藏
      dialogVisible: false,
      // 表单数据
      addForm: {
        name: '',
        loginName: '',
        pwd: '',
        nickname: '',
        phone: '',
        email: '',
        sex: 1
      },
      // 表单验证规则
      addFormRules: {
        name: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 50, message: '用户名的长度在 3 到 50 个字符', trigger: 'blur' }
        ],
        loginName: [
          { required: true, message: '请输入账号', trigger: 'blur' },
          { min: 3, max: 50, message: '用户名的长度在 3 到 50 个字符', trigger: 'blur' }
        ],
        pwd: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 50, message: '用户名的长度在 3 到 50 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: checkPhone, trigger: 'blur' }
        ]
      },
      // 修改对话框控制
      editDialogVisible: false,
      // 查询用户的信息
      editForm: {},
      // 修改表单的验证规则
      editFormRules: {
        name: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 50, message: '用户名的长度在 3 到 50 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: checkPhone, trigger: 'blur' }
        ]
      },
      // 控制设置角色对话框
      setRolesdialogVisible: false,
      setRotes: {
        userid: 0,
        name: '',
        rolesname: '',
        rolesSelect: []
      },
      // 角色下拉选中后的值
      newUserRoles: ''
    }
  },
  created () {
    this.getUserList()
  },
  methods: {
    // 加载用户数据
    async getUserList() {
      // params 组成了 http://localhost:50203/api/GetUserList?query=&pageIndex=1&pageSize=10
      // const { data: res } = await this.$http.get('api/GetUserList', { params: this.queryInfo })
      const { data: res } = await this.$http.get('api/user/getpage', { params: this.queryInfo })
      var json = JSON.parse(res)
      console.log(json.meta.status)
      if (json.meta.status === 200) {
        this.userList = json.data
        this.total = json.data[0].totalcount
      } else {
        this.$msg.error('获取数据失败')
      }
    },
    // 分页功能 监听pageSize
    handleSizeChange (newSize) {
      this.queryInfo.pageSize = newSize
      this.getUserList()
    },
    // 分页功能 监听页码值
    handleCurrentChange (newCurrent) {
      this.queryInfo.pageIndex = newCurrent
      this.getUserList()
    },
    // 监听switch装填的改变
    userStateChanged(userInfo) {
      var that = this
      this.$http.put('/api/state/edit', { id: userInfo.id, isdel: userInfo.isdel + '' }).then(function(ret) {
        var res = JSON.parse(ret.data)
        if (res.meta.status === 200) {
          that.$msg.success('更新状态成功')
        } else {
          userInfo.isdel = !userInfo.isdel
          that.$msg.error('更新状态失败')
        }
      })
    },
    // 取消操作
    resetAddUser () {
      this.dialogVisible = false
    },
    // 添加用户对话框关闭事件
    addDialogClosed () {
      this.addForm.name = ''
      this.addForm.loginName = ''
      this.addForm.pwd = ''
      this.addForm.nickname = ''
      this.addForm.phone = ''
      this.addForm.email = ''
      this.addForm.sex = 1
      this.$refs.addFormRef.resetFields()
    },
    // 添加用户
    subAddUser () {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return false
        var { data: res } = await this.$http.post('api/user/add', this.addForm)
        if (JSON.parse(res).meta.status === 200) {
          this.$msg.success('添加用户成功')
          this.dialogVisible = false
          this.addDialogClosed()
        } else {
          this.$msg.error('添加用户失败')
        }
      })
    },
    // 显示编辑用户的对话框
    async showEditDialog (id) {
      this.editDialogVisible = true
      const { data: res } = await this.$http.get('api/user/get/' + id)
      if (JSON.parse(res).meta.status !== 200) {
        return this.$http.error('查询用户信息失败')
      }
      this.editForm = JSON.parse(res).data
      this.editDialogVisible = true
    },
    // 监听 用户修改对话框 关闭后事件
    editDialogClosed () {
      this.$refs.editFormRef.resetFields()
    },
    // 修改用户信息并提交
    editUserInfo () {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return false
        // 发起修改用户的数据请求
        var { data: res } = await this.$http.put('api/user/put', this.editForm)
        if (JSON.parse(res).meta.status === 200) {
          this.$msg.success('更新用户信息成功')
          // 关闭对话框
          this.editDialogVisible = false
          this.editDialogClosed()
          // 重新获取下数据
          this.getUserList()
        } else {
          this.$msg.error('修改用户信息失败')
        }
      })
    },
    // 根据ID删除用户
    async delUser (id) {
      // console.log(id)
      const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 如果用户确定删除，则返回字符串 confirm
      // 如果用户取消删除，则返回字符串 cancel
      if (confirmResult !== 'confirm') {
        return this.$msg.info('取消删除')
      }
      const { data: res } = await this.$http.delete('api/user/del/' + id)
      if (JSON.parse(res).meta.status !== 200) {
        return this.$msg.error('删除用户失败')
      }
      this.$msg.success('删除成功')
      this.getUserList()
    },
    // 日期显示转换
    getData (strData) {
      const da = new Date(strData)
      const year = da.getFullYear()
      const mouth = da.getMonth() + 1
      const day = da.getDate()
      return year + '-' + mouth + '-' + (day < 10 ? '0' + day : day)
    },
    // 打开设置用户角色对话框
    async setUserRoles(row) {
      console.log(row)
      // 获取原先用户的数据--------------------------
      this.setRotes.userid = row.id
      this.setRotes.name = row.name
      this.setRotes.rolesname = !row.rolename ? '无' : row.rolename
      // ------------------------------------------

      // 获取角色-------------------------------------
      const { data: roles } = await this.$http.get('api/roles/all')
      const rolesjson = JSON.parse(roles)
      if (rolesjson.meta.status !== 200) return this.$msg.error(rolesjson.meta.msg)
      // console.log(rolesjson.data)
      this.setRotes.rolesSelect = rolesjson.data
      // ----------------------------------------------

      this.setRolesdialogVisible = true
    },
    // 提交用户角色配置
    async subSetUserRoles () {
      // console.log(this.newUserRoles, this.setRotes.userid)
      const { data: res } = await this.$http.post('api/user/role/add', { uid: this.setRotes.userid, rid: this.newUserRoles })
      const resjson = JSON.parse(res)
      if (resjson.meta.status !== 200) return this.$msg.error(resjson.meta.msg)
      this.$msg.success('用户角色设置成功')
      this.setRolesdialogVisible = false
    },
    // 用户角色设置对话框关闭后，触发的事件
    userRolesDialogClosed () {
      this.setRotes.userid = 0
      this.setRotes.name = ''
      this.setRotes.rolesname = ''
      this.setRotes.rolesSelect = []
      this.newUserRoles = ''
      this.getUserList()
    }

  }
}
</script>

<style lang="less" scoped>
.el-table{
  margin-top: 10px;
  font-size: 12px;
}
.el-pagination{
  margin-top: 10px;
}
</style>
